/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package narutodownloader;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.Context;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;

/**
 *
 * @author mamat-dev
 */
public class HTMLParser {

    String htmlcode = "";

    public HTMLParser(String code) {
        this.htmlcode = code;
    }

    public String getImageParser() {
        String strImg = "";
        try {
            Parser p = new Parser(this.htmlcode);
            NodeList collectionList = new NodeList();
            TagNameFilter filter = new TagNameFilter("IMG");
            for (NodeIterator e = p.elements(); e.hasMoreNodes();) {
                e.nextNode().collectInto(collectionList, filter);
            }
            if (collectionList.size() != 0) {
                for (SimpleNodeIterator e = collectionList.elements(); e.hasMoreNodes();) {
                    Node node = e.nextNode();
                    String[] str_ = node.getText().split(" ");
                    for (int x = 0; x < str_.length; x++) {
                        Pattern pattern = Pattern.compile("mangas");
                        Matcher m = pattern.matcher(str_[x]);
                        if (m.find()) {
                            strImg = str_[x].replace("src=\"", "").replace("\"", "");
                            break;
                        }
                    }

                }
            }
        } catch (ParserException ex) {
            Logger.getLogger(HTMLParser.class.getName()).log(Level.SEVERE, null, ex);
        }

        return strImg;
    }

    public String getHtmlParser() {
        String context = "";
        try {
            Parser p = new Parser(this.htmlcode);

            NodeList collectionList = new NodeList();
            TagNameFilter filter = new TagNameFilter("p");
            for (NodeIterator e = p.elements(); e.hasMoreNodes();) {
                e.nextNode().collectInto(collectionList, filter);
            }

            if (collectionList.size() != 0) {
                for (SimpleNodeIterator e = collectionList.elements(); e.hasMoreNodes();) {
                    Node node = e.nextNode();
                    context += node.toPlainTextString();
                }
            }
        //System.out.println(context);
        } catch (ParserException ex) {
            Logger.getLogger(HTMLParser.class.getName()).log(Level.SEVERE, null, ex);
        }

        return context;
    }
}
